import { createStore } from 'vuex'

export default createStore({
    state: {
        auth: {
            isAuthenticated: false,
            user: null,
            token: localStorage.getItem('token') || null
        }
    },
    mutations: {
        setAuth(state, { user, token }) {
            state.auth.isAuthenticated = true
            state.auth.user = user
            state.auth.token = token
            localStorage.setItem('token', token)
        },
        clearAuth(state) {
            state.auth.isAuthenticated = false
            state.auth.user = null
            state.auth.token = null
            localStorage.removeItem('token')
        }
    },
    actions: {
        login({ commit }, { user, token }) {
            commit('setAuth', { user, token })
        },
        logout({ commit }) {
            commit('clearAuth')
        },
        fetchCurrentUser({ commit, state }) {
            // 这里应该从API获取当前用户信息
            // 模拟数据
            if (state.auth.token) {
                const user = {
                    id: 1,
                    username: 'admin',
                    name: '系统管理员',
                    role: 'admin'
                }
                commit('setAuth', { user, token: state.auth.token })
            }
        }
    }
})